package com.miao.im.domain;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.annotation.JSONField;
import com.miao.im.common.enums.Gender;
import com.miao.im.dto.AuthRequestDto;
import lombok.Data;
import lombok.experimental.Accessors;

import java.time.LocalDateTime;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/4/11 20:44
 * @Description:
 */
@Data
@Accessors(chain = true)
public class UserDo {
    /**用户id*/
    private Long id;
    private String username;
    private String nickname;
    private String password;
    /**加密用的盐*/
    private String salt;
    /**性别 {@link Gender}*/
    private Integer gender;
    /**头像*/
    private String avatar;
    /**设备号*/
    private String deviceNumber;
    /**最后一次登录时间*/
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime lastLoginTime;
    /**创建时间*/
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;

    public UserDo() {
        this.lastLoginTime = LocalDateTime.now();
        this.createTime = LocalDateTime.now();
    }

    public static UserDo register(AuthRequestDto dto) {
        UserDo webUser = new UserDo();
        webUser.setAvatar(dto.getAvatar());
        webUser.setGender(dto.getGender());
        webUser.setNickname(dto.getNickname());
        webUser.setUsername(dto.getUsername());
        webUser.setDeviceNumber(dto.getDeviceNumber());
        webUser.setSalt(IdUtil.simpleUUID());
        webUser.setPassword(secondEncryptPwd(dto.getPassword(), webUser.getSalt()));
        return webUser;
    }


    private static String secondEncryptPwd(String pwd, String salt) {
        return SecureUtil.md5(pwd + salt);
    }
}
